<template>
  <header class="app-header">
    <div class="header-container">
      <!-- Logo -->
      <div class="logo-section">
        <router-link :to="userStore.isLoggedIn ? '/app/dashboard' : '/'" class="logo">
          <NearLogo :size="32" variant="primary" />
          <span>{{ $t('header.logo') }}</span>
        </router-link>
      </div>

      <!-- Navigation Menu - 登录后显示 -->
      <nav v-if="userStore.isLoggedIn" class="nav-section">
        <div class="nav-menu">
          <router-link
            v-for="item in navigationItems"
            :key="item.name"
            :to="item.path"
            class="nav-item"
            :class="{ active: route.path === item.path }"
          >
            {{ $t(item.label) }}
          </router-link>
        </div>
        <el-dropdown
          trigger="click"
          placement="bottom-end"
          class="mobile-nav-dropdown"
          @command="handleMobileNavCommand"
        >
          <el-button class="mobile-nav-button">
            <span class="mobile-nav-label">{{ currentNavLabel }}</span>
            <Icon icon="mdi:chevron-down" width="16" height="16" />
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item
                v-for="item in navigationItems"
                :key="item.name"
                :command="item.path"
                :class="{ active: route.path.startsWith(item.path) }"
              >
                {{ $t(item.label) }}
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </nav>

      <!-- Empty space for layout when not logged in -->
      <div v-else class="nav-section"></div>

      <!-- Actions -->
      <div class="actions-section">
        <!-- Language Switcher -->
        <el-dropdown
          @command="handleLanguageChange"
          class="language-switcher"
          trigger="click"
          :hide-on-click="true"
          :hide-timeout="300"
          :show-timeout="0"
        >
          <el-button link class="flag-btn">
            <Icon :icon="currentLocale === 'ko' ? 'twemoji:flag-south-korea' : 'twemoji:flag-united-states'" width="20" height="20" />
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="ko">
                <Icon icon="twemoji:flag-south-korea" width="16" height="16" />
                한국어
              </el-dropdown-item>
              <el-dropdown-item command="en">
                <Icon icon="twemoji:flag-united-states" width="16" height="16" />
                English
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>

        <!-- Sign In Button - 未登录时显示 -->
        <router-link v-if="!userStore.isLoggedIn" to="/auth/login">
          <el-button type="primary" class="sign-in-btn">
            {{ $t('header.signIn') }}
          </el-button>
        </router-link>

        <!-- User Menu - 登录后显示 -->
        <el-dropdown
          v-else
          @command="handleUserMenuCommand"
          class="user-menu"
          trigger="click"
          :hide-on-click="true"
          :hide-timeout="300"
          :show-timeout="0"
        >
          <el-button link class="user-btn">
            <Icon icon="mdi:account-circle" width="24" height="24" />
            <span class="user-name">{{ userName }}</span>
            <Icon icon="mdi:chevron-down" width="16" height="16" />
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="profile">
                <Icon icon="mdi:account-edit" width="16" height="16" />
                {{ $t('navigation.profile') }}
              </el-dropdown-item>
              <el-dropdown-item command="account">
                <Icon icon="mdi:account" width="16" height="16" />
                {{ $t('navigation.account') }}
              </el-dropdown-item>
              <el-dropdown-item command="deposit">
                <Icon icon="mdi:wallet-plus" width="16" height="16" />
                {{ $t('navigation.deposit') }}
              </el-dropdown-item>
              <el-dropdown-item command="withdraw">
                <Icon icon="mdi:cash-minus" width="16" height="16" />
                {{ $t('navigation.withdraw') }}
              </el-dropdown-item>
              <el-dropdown-item divided command="logout">
                <Icon icon="mdi:logout" width="16" height="16" />
                {{ $t('header.logout') }}
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>
  </header>

  <!-- 用户信息编辑对话框 -->
  <UserInfoEditDialog
    v-model="profileDialogVisible"
    @updated="handleUserInfoUpdated"
  />
</template>

<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import type { Ref } from 'vue'
import { storeToRefs } from 'pinia'
import { useRoute, useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { Icon } from '@iconify/vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore, type UserInfo } from '@/stores/user'
import NearLogo from '@/components/Common/NearLogo.vue'
import UserInfoEditDialog from '@/components/User/UserInfoEditDialog.vue'

const router = useRouter()
const route = useRoute()
const { locale, t } = useI18n()
const userStore = useUserStore()
const { userInfo: storeUserInfo } = storeToRefs(userStore) as unknown as {
  userInfo: Ref<UserInfo | null>
}
const userName = computed(() => storeUserInfo.value?.name ?? 'User')

const currentLocale = computed(() => locale.value)
const profileDialogVisible = ref(false)

// 导航菜单项
const navigationItems = [
  { name: 'wallet', path: '/app/dashboard', label: 'navigation.wallet' },
  { name: 'staking', path: '/app/staking', label: 'navigation.staking' },
  { name: 'explore', path: '/app/explore', label: 'navigation.explore' },
  { name: 'account', path: '/app/account', label: 'navigation.account' },
  { name: 'support', path: '/app/support', label: 'navigation.support' }
]

const handleLanguageChange = (command: string) => {
  locale.value = command
}

const handleUserMenuCommand = async (command: string) => {
  if (command === 'profile') {
    profileDialogVisible.value = true
  } else if (command === 'account') {
    router.push('/app/account')
  } else if (command === 'deposit') {
    router.push('/app/deposit')
  } else if (command === 'withdraw') {
    router.push('/app/withdraw')
  } else if (command === 'logout') {
    try {
      await ElMessageBox.confirm(
        t('header.logoutConfirm'),
        t('header.logout'),
        {
          confirmButtonText: t('header.confirmLogout'),
          cancelButtonText: t('header.cancel'),
          type: 'warning',
        }
      )

      userStore.logout()
      ElMessage.success(t('header.logoutSuccess'))
      router.push('/auth/login')
    } catch {
      // 用户取消
    }
  }
}

const currentNavItem = computed(() => {
  return navigationItems.find(item => route.path.startsWith(item.path)) ?? navigationItems[0]
})

const currentNavLabel = computed(() => {
  return t(currentNavItem.value.label)
})

const handleMobileNavCommand = (path: string) => {
  router.push(path)
}

// 初始化用户状态
onMounted(() => {
  userStore.initializeAuth()
})

// 处理用户信息更新
const handleUserInfoUpdated = () => {
  // 刷新用户信息
  userStore.fetchUserProfile()
}
</script>

<style scoped lang="scss">
.app-header {
  background: white;
  border-bottom: 1px solid #e2e8f0;
  position: sticky;
  top: 0;
  z-index: 1000;

  .header-container {
    max-width: 1200px;
    margin: 0 auto;
    padding: 0 24px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 64px;
  }

  .logo-section {
    .logo {
      display: flex;
      align-items: center;
      gap: 8px;
      font-size: 16px;
      font-weight: 600;
      color: #1a202c;
      cursor: pointer;

      svg {
        color: #7c3aed;
      }
    }
  }

  .nav-section {
    flex: 1;
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 16px;

    .nav-menu {
      display: flex;
      gap: 32px;

      .nav-item {
        position: relative;
        color: #64748b;
        font-weight: 500;
        font-size: 15px;
        text-decoration: none;
        padding: 8px 16px;
        border-radius: 8px;
        transition: all 0.2s ease;

        &:hover {
          color: #7c3aed;
          background: #f8fafc;
        }

        &.active {
          color: #7c3aed;
          font-weight: 600;

          &::after {
            content: '';
            position: absolute;
            bottom: -20px;
            left: 50%;
            transform: translateX(-50%);
            width: 24px;
            height: 3px;
            background: #7c3aed;
            border-radius: 2px;
          }
        }
      }
    }
  }

    .mobile-nav-dropdown {
      display: none;
    }
  }

  .actions-section {
    display: flex;
    align-items: center;
    gap: 12px;

    .language-switcher {
      .flag-btn {
        padding: 8px !important;
        border: none !important;
        background: transparent !important;
        border-radius: 8px;
        transition: all 0.2s ease;
        min-width: 40px;
        min-height: 40px;
        display: flex;
        align-items: center;
        justify-content: center;

        &:hover {
          background: #f7fafc !important;
        }

        &:active {
          background: #e2e8f0 !important;
          transform: scale(0.95);
        }
      }
    }

    .sign-in-btn {
      background: #7c3aed;
      border: none;
      border-radius: 8px;
      padding: 8px 16px;
      font-weight: 500;
      font-size: 14px;
      height: 36px;
      min-height: 36px;

      &:hover {
        background: #6d28d9;
      }
    }

    .user-menu {
      .user-btn {
        display: flex;
        align-items: center;
        gap: 8px;
        padding: 8px 12px !important;
        border: none !important;
        background: transparent !important;
        border-radius: 8px;
        transition: all 0.2s ease;
        color: #374151;
        min-height: 40px;

        &:hover {
          background: #f7fafc !important;
          color: #7c3aed;
        }

        &:active {
          background: #e2e8f0 !important;
          transform: scale(0.98);
        }

        .user-name {
          font-weight: 500;
          font-size: 14px;
        }

        svg:first-child {
          color: #7c3aed;
        }

        svg:last-child {
          color: #9ca3af;
        }
      }
    }
  }


// Element Plus 样式覆盖
:deep(.el-button) {
  border: none;
}

:deep(.el-dropdown-menu) {
  border-radius: 8px;
  border: 1px solid #e2e8f0;
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
  padding: 4px;

  .el-dropdown-menu__item {
    border-radius: 6px;
    margin: 2px 0;
    padding: 12px 16px;
    font-size: 14px;
    min-height: 44px;
    display: flex;
    align-items: center;
    gap: 8px;
    transition: all 0.2s ease;

    &:hover {
      background: #f7fafc;
    }

    &:active {
      background: #e2e8f0;
      transform: scale(0.98);
    }
  }
}

@media (max-width: 768px) {
  .app-header {
    .header-container {
      padding: 0 16px;
    }

    .nav-section {
      justify-content: center;

      .nav-menu {
        display: none;
      }

      .mobile-nav-dropdown {
        display: inline-flex;
      }
    }

    .actions-section {
      gap: 8px;

      .language-switcher .flag-btn {
        min-width: 44px;
        min-height: 44px;
        padding: 10px !important;
      }

      .user-menu {
        .user-btn {
          min-height: 44px;
          padding: 10px !important;

          .user-name {
            display: none; // 移动端隐藏用户名
          }
        }
      }
    }
  }

  // 移动端下拉菜单样式优化
  :deep(.el-dropdown-menu) {
    min-width: 200px;
    margin-top: 8px;

    .el-dropdown-menu__item {
      padding: 16px 20px;
      min-height: 48px;
      font-size: 16px;

      &:active {
        background: #e2e8f0;
        transform: none; // 移动端不使用缩放效果
      }
    }
  }
}

.mobile-nav-dropdown {
  .mobile-nav-button {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    border: 1px solid #e2e8f0;
    border-radius: 8px;
    padding: 6px 12px;
    color: #475569;
    background: #ffffff;
    font-weight: 600;
    transition: background 0.2s ease, border 0.2s ease, color 0.2s ease;

    &:hover {
      background: #f8fafc;
      border-color: #c7d2fe;
      color: #4338ca;
    }

    .mobile-nav-label {
      max-width: 140px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }
}

:deep(.el-dropdown-menu__item.active) {
  background: #ede9fe;
  color: #7c3aed;
}
</style>
